package com.youlu.campus.admin.task;

import com.youlu.campus.entity.PlatformConfig;
import com.youlu.campus.service.order.OrderService;
import com.youlu.campus.service.platform.PlatformConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class WechatMiniOrderRefundTask {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private OrderService orderService;
    @Autowired
    private PlatformConfigService platformConfigService;

    /**
     * 1分钟执行一次
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void doRefundOrderJob() {
        PlatformConfig platformConfig = platformConfigService.find();
        log.info("开始执行:>>> 小程序订单退款申请:0 0/5 * * * ?,自动退款模式:{}", platformConfig.getWechatMiniAutoRefund());
        if (!Boolean.TRUE.equals(platformConfig.getWechatMiniAutoRefund())) {
            log.info("小程序订单退款非自动退款.....");
        }
        Boolean flag = redisTemplate.opsForValue().setIfAbsent("wechat-mini-refund:order:status", "1", 10L, TimeUnit.MINUTES);
        log.info("开始执行:>>> 小程序订单退款申请锁状态:{}", flag);
        if (Objects.nonNull(flag) && Boolean.FALSE.equals(flag)) {
            return;
        }
        orderService.doWechatMiniRefundOrder("wechat-mini");
        Boolean dLock = redisTemplate.delete("wechat-mini-refund:order:status");
        log.info("结束执行:>>> 小程序订单退款释放锁状态:{}", dLock);
    }
    /**
     * 3分钟执行一次
     */
    @Scheduled(cron = "0 0/3 * * * ?")
    public void doH5RefundOrderJob() {
        PlatformConfig platformConfig = platformConfigService.find();
        log.info("开始执行:>>> 小程序订单退款申请:0 0/3 * * * ?,自动退款模式:{}", platformConfig.getWechatMiniAutoRefund());
        if (!Boolean.TRUE.equals(platformConfig.getWechatH5AutoRefund())) {
            log.info("H5订单退款非自动退款.....");
        }
        Boolean flag = redisTemplate.opsForValue().setIfAbsent("wechat-h5-refund:order:status", "1", 20L, TimeUnit.MINUTES);
        log.info("开始执行:>>> H5订单退款申请锁状态:{}", flag);
        if (Objects.nonNull(flag) && Boolean.FALSE.equals(flag)) {
            return;
        }
        orderService.doWechatH5RefundOrder("wechat-mini");
        Boolean dLock = redisTemplate.delete("wechat-h5-refund:order:status");
        log.info("结束执行:>>> H5订单退款释放锁状态:{}", dLock);
    }
}
